package com.isyscore.os.metadata.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.isyscore.boot.login.LoginUserManager;
import com.isyscore.os.core.exception.DataFactoryException;
import com.isyscore.os.core.util.InitiallyUtils;
import com.isyscore.os.metadata.common.CommonService;
import com.isyscore.os.metadata.dao.MetricGroupMapper;
import com.isyscore.os.metadata.model.dto.req.ChangeMetricGroupNameReq;
import com.isyscore.os.metadata.model.entity.Metric;
import com.isyscore.os.metadata.model.entity.MetricGroup;
import com.isyscore.os.permission.common.constants.PermissionConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.isyscore.os.core.exception.ErrorCode.DATA_NOT_FOUND;
import static com.isyscore.os.metadata.constant.CommonConstant.DEFAULT_METRIC_GROUP_ID;
import static java.util.Collections.emptyList;

/**
 * <p>
 * 数据指标分组 服务实现类
 * </p>
 *
 * @author
 * @since 2021-08-11
 */
@Service
@Transactional
public class MetricGroupService extends CommonService<MetricGroupMapper, MetricGroup> {

    @Autowired
    private MetricService metricService;

    @Autowired
    private LoginUserManager loginUserManager;

    public MetricGroup createMetricGroup(String groupName) {
        MetricGroup metricGroup = new MetricGroup();
        metricGroup.setGroupName(groupName);
        this.save(metricGroup);
        return metricGroup;
    }

    public MetricGroup getGroupById(Long groupId) {
        MetricGroup metricGroup = null;
        //如果是查询全局默认分组，需要忽略租户进行查询
        if (groupId == -1) {
            metricGroup = InitiallyUtils.markInitially(() -> this.getById(groupId));
        } else {
            metricGroup = this.getById(groupId);
        }
        if (metricGroup == null) {
            throw new DataFactoryException(DATA_NOT_FOUND, "该指标分组不存在");
        }
        return metricGroup;
    }

    public void updateMetricGroupName(MetricGroup metricGroup, ChangeMetricGroupNameReq req) {
        if (metricGroup == null) {
            throw new DataFactoryException(DATA_NOT_FOUND, "指标分组");
        }
        metricGroup.setGroupName(req.getGroupName());
        this.updateById(metricGroup);
    }

    public void deleteMetricGroup(MetricGroup metricGroup) {
        if (metricGroup == null) {
            throw new DataFactoryException(DATA_NOT_FOUND, "指标分组");
        }
        LambdaQueryWrapper<Metric> qw = new LambdaQueryWrapper<>();
        qw.eq(Metric::getGroupRefId, metricGroup.getId());
        List<Metric> metrics = metricService.list(qw);
        this.removeById(metricGroup.getId());
        for (Metric metric : metrics) {
            metric.setGroupRefId(DEFAULT_METRIC_GROUP_ID);
            metricService.updateById(metric);
        }
    }

    public void importData(List<MetricGroup> metricGroups) {
        if (metricGroups.isEmpty()) {
            return;
        }
        Set<Long> ids = metricGroups.stream().map(MetricGroup::getId).collect(Collectors.toSet());
        LambdaQueryWrapper<MetricGroup> qw = new LambdaQueryWrapper<MetricGroup>();
        qw.in(MetricGroup::getId, ids);
        this.remove(qw);
        this.saveBatch(metricGroups);
    }

    public List<MetricGroup> getDataByIds(Set<String> ids) {
        if (ids.isEmpty()) {
            return emptyList();
        }
        LambdaQueryWrapper<MetricGroup> qw = new LambdaQueryWrapper<MetricGroup>();
        qw.in(MetricGroup::getId, ids);
        return this.list(qw);
    }

    @Override
    public List<MetricGroup> list() {
        //处理默认全局分组的加载
        LambdaQueryWrapper<MetricGroup> qw = new LambdaQueryWrapper<>();
        qw.eq(MetricGroup::getTenantId, loginUserManager.getCurrentTenantId())
                .or()
                .eq(MetricGroup::getTenantId, PermissionConstants.GLOBAL_BUSINESS_DATA_TENANT_ID_KEY);
        return InitiallyUtils.markInitially(() -> this.baseMapper.selectList(qw));
    }

    @Override
    public List<MetricGroup> list(Wrapper<MetricGroup> wrapper) {
        if (wrapper == null) {
            return list();
        }
        LambdaQueryWrapper<MetricGroup> qw = (LambdaQueryWrapper<MetricGroup>) wrapper;
        qw.eq(MetricGroup::getTenantId, loginUserManager.getCurrentTenantId())
                .or()
                .eq(MetricGroup::getTenantId, PermissionConstants.GLOBAL_BUSINESS_DATA_TENANT_ID_KEY);
        return InitiallyUtils.markInitially(() -> this.baseMapper.selectList(qw));
    }
    public List<MetricGroup> listByCurrentTenant(Wrapper<MetricGroup> wrapper) {
        if (wrapper == null) {
            return list();
        }
        LambdaQueryWrapper<MetricGroup> qw = (LambdaQueryWrapper<MetricGroup>) wrapper;
        return this.baseMapper.selectList(qw);
    }


}
